#!/usr/bin/env node

const http = require('http'),
      qs   = require('querystring'),
      fs   = require('fs'),
      log  = console.log;

let items = ['eat','sleeping'];
let result = {
  status1:200,
  reason:'ok'
};

http.createServer((req,res)=>{
  logRequest(req);
  if(req.url.slice(0,5) !== '/todo'){
    let html = fs.readFileSync('./12-todo.html').toString('utf8');
    if(req.url === '/'){
      res.end(html);
    }else if(req.url == '/12-todo.js'){
      fs.createReadStream('./12-todo.js').pipe(res);
    }else{
      res.end('not api request and not page request!');
    }
    return;
  }
  switch(req.method){
    case 'GET':
      select(req, res);
      break;

    case 'POST':
      insert(req,res);
      break;

    case 'PUT':
      update(req,res);
      break;

    case 'DELETE':
      del(req,res);
      break;
    
    default:
      res.end(`${req.method}  method not support`);
      break;
  }
  
}).listen(8080);

function logRequest(req){
  log(`${req.method}  ${req.url} ${req.httpVersion}`);
  log();
}

function select(req,res){
  result.data = items;
  res.end(JSON.stringify(result));
}
function insert(req,res){
  let data = '';

  req.on('data',(chunck)=> data+=chunck);
  req.on('end',()=>{
    let item = qs.parse(data).item;
    if(item !=='' && typeof item !== 'undefined'){
      items.push(item);
      res.end(JSON.stringify(result));
    }else if(req.url == '/12-todo.js'){
      fs.createWriteStream('./12-todo.js').pipe(res);
    }
    else{
      result.status1 = 401;
      result.reason = 'item is empty';
      res.end(result);
    }
  });
}
function update(req,res){
  //1.get id
  let id = req.url.split(':')[1];
  //数据合法性校验：data type、value min=0 max=items.length
  

  //2.get item,获取请求体
  let data = '';
  req.on('data',chunck => data+=chunck);

  req.on('end',()=>{
    let item = qs.parse(data).item;
    if(item !=='' && typeof item !=='undefined' ){
      items[id] = item;
      res.end(JSON.stringify(result));
    }else{
      result.status1 = 401;
      result.reason = 'item is empty';
      res.end(result);
    }
  });
  
  //3.update items[id] = item
  
}
function del(req,res){
  
  //get id
  let id = req.url.split(':')[1];

  //id not exist del all
  if(typeof id ==='undefined'){
    items = [];
    result.status1 = 200;
    result.reason  ='delete all success';
    res.end(JSON.stringify(result));
    return;
  }
  //id exist 
  items.splice(id,1);
  result.status1 = 200;
  result.reason = 'del success';
  res.end(JSON.stringify(result));
  //id isok del items[id]
}



